<template>
  <div class="admin-orders">
    <!-- 侧边栏 -->
    <admin-sidebar ref="sidebarRef" :class="{ collapsed: sidebarCollapsed }" />

    <!-- 主内容区 -->
    <div class="main-content" :class="{ 'sidebar-collapsed': sidebarCollapsed }">
      <!-- 顶部导航 -->
      <admin-header 
        page-title="订单管理"
        :sidebar-collapsed="sidebarCollapsed"
        @toggle-sidebar="toggleSidebar"
      />

      <!-- 内容区域 -->
      <div class="content">
        <el-card shadow="hover">
          <div class="card-header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索订单号/用户名"
              prefix-icon="Search"
              class="search-input"
            >
              <template #append>
                <el-button type="primary" @click="handleSearch">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
              </template>
            </el-input>
            <el-select v-model="filterStatus" placeholder="订单状态" class="filter-select">
              <el-option label="全部" value=""></el-option>
              <el-option label="未支付" value="0"></el-option>
              <el-option label="已支付" value="1"></el-option>
              <el-option label="已退款" value="2"></el-option>
            </el-select>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              class="date-picker"
            />
          </div>

          <el-table
            :data="paginatedOrders"
            style="width: 100%"
            border
            stripe
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="订单ID" width="80"></el-table-column>
            <el-table-column prop="orderNumber" label="订单号"></el-table-column>
            <el-table-column prop="userName" label="用户名称"></el-table-column>
            <el-table-column prop="courseName" label="课程名称"></el-table-column>
            <el-table-column prop="amount" label="订单金额" width="120">
              <template #default="scope">
                ¥{{ scope.row.amount }}
              </template>
            </el-table-column>
            <el-table-column prop="payMethod" label="支付方式" width="120">
              <template #default="scope">
                {{ scope.row.payMethod === 1 ? '微信' : '支付宝' }}
              </template>
            </el-table-column>
            <el-table-column prop="payStatus" label="支付状态" width="120">
              <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row.payStatus)">
                  {{ getStatusText(scope.row.payStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="orderTime" label="下单时间"></el-table-column>
            <el-table-column prop="checkoutTime" label="支付时间">
              <template #default="scope">
                {{ scope.row.checkoutTime || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button type="primary" text @click="viewOrderDetail(scope.row)">查看</el-button>
                <el-button type="danger" text @click="handleRefund(scope.row)" v-if="scope.row.payStatus === '1'">
                  退款
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="filteredOrders.length"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import AdminSidebar from '@/components/AdminSidebar.vue'
import AdminHeader from '@/components/AdminHeader.vue'
import { Search } from '@element-plus/icons-vue'

const router = useRouter()
const sidebarCollapsed = ref(false)
const sidebarRef = ref()

// 管理员信息
const adminInfo = computed(() => {
  const info = localStorage.getItem('adminInfo')
  if (info) {
    return JSON.parse(info)
  }
  return { name: '管理员' }
})
const isSuperAdmin = computed(() => {
  const info = localStorage.getItem('adminInfo')
  if (info) {
    return JSON.parse(info).isSuperAdmin || false
  }
  return false
})

// 切换侧边栏
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
}

// 搜索和筛选
const searchKeyword = ref('')
const filterStatus = ref('')
const dateRange = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10
})

// 选中的订单
const selectedOrders = ref([])

// 模拟订单数据
const orders = ref([
  {
    id: 1,
    orderNumber: '202401200001',
    userId: 1,
    userName: '张三',
    courseId: 1,
    courseName: 'Vue3 从入门到精通',
    amount: 199,
    payMethod: 2,
    payStatus: '1',
    orderTime: '2024-01-20 10:30:00',
    checkoutTime: '2024-01-20 10:35:00'
  },
  {
    id: 2,
    orderNumber: '202401200002',
    userId: 2,
    userName: '李四',
    courseId: 2,
    courseName: 'Spring Boot 实战开发',
    amount: 299,
    payMethod: 1,
    payStatus: '1',
    orderTime: '2024-01-20 11:20:00',
    checkoutTime: '2024-01-20 11:22:00'
  },
  {
    id: 3,
    orderNumber: '202401200003',
    userId: 3,
    userName: '王五',
    courseId: 3,
    courseName: 'React Native 移动开发',
    amount: 399,
    payMethod: 2,
    payStatus: '0',
    orderTime: '2024-01-20 14:05:00'
  },
  {
    id: 4,
    orderNumber: '202401190001',
    userId: 1,
    userName: '张三',
    courseId: 2,
    courseName: 'Spring Boot 实战开发',
    amount: 299,
    payMethod: 1,
    payStatus: '2',
    orderTime: '2024-01-19 16:40:00',
    checkoutTime: '2024-01-19 16:45:00'
  }
])

// 筛选后的订单
const filteredOrders = computed(() => {
  return orders.value.filter(order => {
    const matchesKeyword = !searchKeyword.value || 
      order.orderNumber.includes(searchKeyword.value) || 
      order.userName.includes(searchKeyword.value)
    const matchesStatus = !filterStatus.value || order.payStatus === filterStatus.value
    
    let matchesDateRange = true
    if (dateRange.value && dateRange.value.length === 2) {
      const orderDate = new Date(order.orderTime)
      const startDate = new Date(dateRange.value[0])
      const endDate = new Date(dateRange.value[1])
      matchesDateRange = orderDate >= startDate && orderDate <= endDate
    }
    
    return matchesKeyword && matchesStatus && matchesDateRange
  })
})

// 分页后的订单
const paginatedOrders = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return filteredOrders.value.slice(start, end)
})

// 处理菜单选择
const handleMenuSelect = (key, keyPath) => {
  activeMenu.value = key
}

// 处理退出登录
const handleLogout = () => {
  localStorage.removeItem('adminToken')
  localStorage.removeItem('adminInfo')
  ElMessage.success('退出成功')
  router.push('/admin/login')
}

// 处理个人信息
const handleProfile = () => {
  ElMessage.info('个人信息功能开发中')
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case '0': return '未支付'
    case '1': return '已支付'
    case '2': return '已退款'
    default: return '未知'
  }
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case '0': return 'warning'
    case '1': return 'success'
    case '2': return 'danger'
    default: return 'info'
  }
}

// 查看订单详情
const viewOrderDetail = (order) => {
  ElMessage.info(`查看订单ID: ${order.id} 的详情`)
}

// 处理退款
const handleRefund = (order) => {
  ElMessageBox.confirm(
    `确定要对订单「${order.orderNumber}」进行退款处理吗？`,
    '退款确认',
    {
      confirmButtonText: '确定退款',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      // 模拟退款操作
      const index = orders.value.findIndex(item => item.id === order.id)
      if (index !== -1) {
        orders.value[index].payStatus = '2'
        ElMessage.success('退款成功')
      }
    })
    .catch(() => {
      // 取消退款
    })
}

// 处理选择变更
const handleSelectionChange = (selection) => {
  selectedOrders.value = selection
}

// 处理搜索
const handleSearch = () => {
  // 重置为第一页
  pagination.currentPage = 1
}

// 页容量发生改变时的处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
}

const handleCurrentChange = (current) => {
  pagination.currentPage = current
}

// 检查登录状态 - 开发阶段完全禁用
const checkLoginStatus = () => {
  // 开发阶段跳过登录验证
  // const adminToken = localStorage.getItem('adminToken')
  // if (!adminToken || !adminInfo.username) {
  //   ElMessage.error('请先登录')
  //   router.push('/admin/login')
  // }
}

onMounted(() => {
  // 注释掉登录验证，方便开发测试
  // checkLoginStatus()
})
</script>

<style scoped>
.admin-orders {
  display: flex;
  height: 100vh;
  background-color: #f0f2f5;
}

.main-content {
  flex: 1;
  margin-left: 250px;
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
  transition: margin-left 0.3s;
}

.main-content.sidebar-collapsed {
  margin-left: 64px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    margin-left: 200px;
  }
  
  .main-content.sidebar-collapsed {
    margin-left: 64px;
  }
}

.content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.card-header-actions {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.filter-select {
  width: 150px;
}

.date-picker {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>